#include "zhelpers.h"
#include "proto.msg.pb.h"
#include "thread.h"
#include "server.h"
#include "Log.h"
#include "vs_opencv.h"
#include "GlobalFeature_API.h"

int thread::send_error_reply(void *zmq, char *reason){
	proto::error_reply resp;
	resp.mutable_head()->set_version(420);
	resp.mutable_head()->set_command(420);
	resp.mutable_head()->set_password("xxxxxxxx", 8);
	resp.mutable_head()->set_type(1);
	resp.mutable_head()->set_status(-1);
	resp.mutable_head()->set_src(0);
	resp.mutable_head()->set_dest(0);
	resp.mutable_head()->set_sn_high(123456789);
	resp.mutable_head()->set_sn_low(123456789);
	resp.mutable_head()->set_length(0);

	resp.set_reason(reason);

	string serial_stream;
	if(!resp.SerializePartialToString(&serial_stream)){
		LOG_ERROR_VA("error reply: fail to serial data");
		return -1;
	}
	zmq_msg_t msg;
	zmq_msg_init_size(&msg, serial_stream.size());
	memcpy(zmq_msg_data(&msg), serial_stream.c_str(), serial_stream.size());
	int size = zmq_sendmsg(zmq, &msg, 0);
	if(size == -1){
		LOG_ERROR_VA("error reply: zmq_sendmsg ERROR");
		return -1;
	}
	return 0;
}

const char* thread::get_name(){
	return get_thread_pool()->get_server()->get_name().c_str();
}

address thread::back_address(){
	return get_thread_pool()->get_server()->get_back_address();
}
	
int thread::thread_func(){
	LOG_ERROR_VA("wrong thread");
	return -1;
}

int thread_pool::start(){
	LOG_INFO_VA("[%s] thread_pool start thread num: %d", get_server()->get_name().c_str(), _thread_num);
	//create all threads
	//for(int i = 0; i < _thread_num; i++){
	//	thread *p = new thread(this);
	//	_thread_vec.push_back(p);
	//}

	//start all the threads
	for (vector<thread *>::iterator it = _thread_vec.begin(); it != _thread_vec.end(); it++){
		(*it)->start();
	}
}

int thread_pool::stop(){
	_stop = false;
	return 0;
	//the diffence beteew this and ~thread_pool()
}

void* thread_pool::get_zmq(){
	return _server->get_zmq();
}

database *match_thread_pool::get_data_base(){
	//return _server->get_data_base();
	//return static_cast<match_server *>(_server)->get_data_base();
	match_server *svr = static_cast<match_server *>(get_server());
	return svr->get_database();
}

